import { defineStore } from 'pinia'
import { resetRouter } from '@/router'
import { useTagsStore, usePermissionStore } from '@/store'
import { removeToken, toLogin } from '@/utils'
import api from '@/api'

export const useUserStore = defineStore('user', {
  state() {
    return {
      userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}'),
      systemList: JSON.parse(localStorage.getItem('systemList') || '[]'),
    }
  },
  getters: {
    userId() {
      return this.userInfo?.id
    },
    name() {
      return this.userInfo?.name
    },
    headpic() {
      return this.userInfo?.avatar
    },
    role() {
      return this.userInfo?.authList || []
    },
  },
  actions: {
    async getLoginUser() {
      try {
        const { code, data } = await api.getLoginUser()
        if (code === 200) {
          const { code: code2, data: data2 } = await api.getLoginMenu()
          if (code2 === 200) {
            const authList = []

            data2.map((v) => {
              v.children.map((c) => {
                authList.push(c.name)

                if (c.children) {
                  c.children.map((cc) => {
                    authList.push(cc.name)

                    if (cc.children) {
                      cc.children.map((ccc) => {
                        authList.push(ccc.name)
                      })
                    }
                  })
                }
              })
            })

            const userInfo = {
              ...data,
              authList,
            }
            this.setUserInfo(userInfo)
            return Promise.resolve(userInfo)
          }
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    async logout() {
      const { resetTags } = useTagsStore()
      const { resetPermission } = usePermissionStore()
      removeToken()
      this.removeUserInfo()
      resetTags()
      resetPermission()
      resetRouter()
      this.$reset()
      toLogin()
    },
    setUserInfo(userInfo = {}) {
      this.userInfo = { ...this.userInfo, ...userInfo }
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
    removeUserInfo() {
      this.userInfo = {}
      localStorage.setItem('userInfo', '{}')
    },
    setSystemList(systemList = []) {
      this.systemList = systemList
      localStorage.setItem('systemList', JSON.stringify(this.systemList))
    },
  },
})
